package cn.pconline.autoclub.util;

import cn.pconline.whoisfront.message.Area;
import cn.pconline.whoisfront.message.Ip;
import cn.pconline.whoisfront.publisher.IpService;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;

public class WhoisUtil {
    private static IpService ipService = IpService.getInstance();
    
    public static JSONObject getProvinceAndCity(String ip) {
        Ip ipObj = ipService.getIpObj(ip, "");
        JSONObject json = getArea(ipObj);
        return json;
    }

    public static String getIp(HttpServletRequest request) {
        return ipService.getIP(request);
    }
    
    public static JSONObject getProvinceAndCity(HttpServletRequest request) {
        Ip ipObj = ipService.getIpObj(request);
        return getArea(ipObj);
        
    }
    
    public static String getNameByCode(int areaCode) {
        Area area = ipService.getAreaByCode(areaCode);
        if(area != null) {
            return area.getAreaName();
        }
        return "";
    }
    
    private static JSONObject getArea(Ip ipObj) {
        JSONObject json = new JSONObject();
        if (ipObj != null) {
            Area areaIp = ipService.getAreaByCode(ipObj.getAreaCode());
            if (areaIp.getAreaLevel() == 2) { // 市
                Area areaBy = areaIp;
                Area parent = ipService.getAreaByCode(areaBy.getPAreaCode());
                json.put("areaName", parent.getAreaName());
                json.put("areaCode", parent.getAreaCode());
                json.put("cityName", areaBy.getAreaName());
                json.put("cityCode", areaBy.getAreaCode());
            } else if (areaIp.getAreaLevel() == 1) { // 省
                json.put("areaName", areaIp.getAreaName());
                json.put("areaCode", areaIp.getAreaCode());
                json.put("cityName", "null");
                json.put("cityCode", "null");
            } else if (areaIp.getAreaLevel() == 3) { // 区
                Area city = ipService.getAreaByCode(areaIp.getPAreaCode());
                Area area = ipService.getAreaByCode(city.getPAreaCode());
                json.put("areaName", area.getAreaName());
                json.put("areaCode", area.getAreaCode());
                json.put("cityName", city.getAreaName());
                json.put("cityCode", city.getAreaCode());
            }
        }
        return json;
    }
}
